package tvs;

import java.sql.ResultSet;
import java.sql.SQLException;

import db.TvsDB;

public class Login {
	
	public Login()
	{}
	
	public static String loginPlayer(String ip, String username, String password)
	{
		Boolean success = false;
		String query = "SELECT * from player where username ='"+ username + "';";
		if(LobbyService.playerList.listDoesntContains(username))
		{
			ResultSet rs = TvsDB.openDB(query);
			try {
				if(rs.next())
				{
					String qryPass = rs.getString("password");
					if(password.equals(qryPass))
					{
						success = true;
						int qryWin = rs.getInt("win");
						int qryLoss = rs.getInt("loss");
						String qryPlayername = rs.getString("playername");
						String qryEmail = rs.getString("email");
						System.out.println("win "+qryWin+" loss "+qryLoss);
						LobbyService.playerList.addPlayer(new Player(ip, username, qryWin, qryLoss, qryPlayername,qryEmail));
					}
					else
						success = false;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		TvsDB.closeDB();
		return success ? "success" : "failure";
	}
	
	public static String getSalt(String username)
	{
		Boolean success = false;
		String query = "SELECT * from player WHERE username ='"+ username+"';";
		String salt = "error";
		ResultSet rs = TvsDB.openDB(query);
		try {
			if(rs.next())
			{
				salt = rs.getString("salt");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		TvsDB.closeDB();
		return salt;
	}
	
	public static String registerUser(String username, String password, String playername, String email)
	{
		String query = "INSERT INTO Player " +
                "VALUES (NULL, '"+username+"', '"+password+"','" + playername+"','"+email +"',0, 0, '')";
		String returnValue = "failure";
		try{
			returnValue = TvsDB.updateDB(query);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return returnValue;
	}
	
	public static String insertSalt(String username, String salt)
	{
		String query = "UPDATE Player "+
		"SET salt='"+salt+"' "+
		"WHERE username='"+username+"';";
		TvsDB.updateDB(query);
		return "success";
	}

}
